import React, { Component } from "react";
import { Modal, Form, Upload, Button, Select, Input, message, Tag } from "antd";
import { connect } from "dva";
import TargetSelectModal from "../add/components/TargetSelectModal";
import styles from "./PushModal.less";

const { TextArea } = Input;
const { Option } = Select;

@Form.create()
@connect(stores => ({
  planData: stores.planlist,
}))
class PushModal extends Component {
  state = {
    url: "",
    modelVisible: false,
    people: [],
    peopleName: [],
    borderVisible: false,
  };

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: "targetPersonSelectModel/reset", // 推送目标应该清空列表
    });
  }

  normFile = e => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  handleSubmit = e => {
    const { handleOk, dispatch } = this.props;
    const { url } = this.state;
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (this.state.people.length <= 0) {
        this.setState({
          borderVisible: true,
        });
      }
      if (!err) {
        if (!values.pushText && url === "") {
          message.error("请填写推送文本或上传推送图片");
          return;
        }
        const content = [];
        if (values.pushText) {
          content.push({
            type: "TEXT",
            content: values.pushText,
          });
        }
        if (url !== "") {
          content.push({
            type: "IMAGE",
            content: url,
          });
        }
        let pushChannelName = "";
        this.props.channelList.forEach(item => {
          if (item.pushChannelId === values.pushChannel) {
            pushChannelName = item.description;
          }
        });
        const pushUserIds = [];
        this.state.people.forEach((item, index) => {
          pushUserIds.push({
            key: item,
            name: this.state.peopleName[index],
          });
        });

        dispatch({
          type: "planlist/artificialPush",
          payload: {
            contents: content,
            msgTitle: values.templateName,
            msgDescription: values.templateDescription,
            pushChannelId: values.pushChannel,
            pushChannelName,
            pushUserIds,
          },
        }).then(() => {
          const { planData } = this.props;
          const { artificialCode } = planData;
          if (artificialCode === 0) {
            message.success("人工推送成功");
            dispatch({
              type: "planlist/planList",
              payload: {
                pageNum: "1",
                pageSize: "10",
                orderByClause: "time_create",
                ascOrDesc: "desc",
              },
            });
          } else {
            message.error("人工推送失败");
          }
        });
        handleOk();
      }
    });
  };

  setUrl = e => {
    const { response } = e.file;
    this.setState({
      url: response && response.datas ? response.datas : "",
    });
  };

  onCancel = () => {
    this.setState({
      modelVisible: false,
    });
  };

  setVisible = () => {
    this.setState({
      modelVisible: true,
    });
  };

  getPeople = (people, peopleName) => {
    if (people) {
      this.setState(
        {
          people,
          peopleName,
          modelVisible: false,
          borderVisible: false,
        },
        () => {
          this.props.form.setFieldsValue({ pushTarget: 1 });
        },
      );
    }
  };

  onCloseTag = indexs => {
    const { people, peopleName } = this.state;
    this.setState(
      {
        people: people.filter((item, index) => index !== indexs),
        peopleName: peopleName.filter((item, index) => index !== indexs),
      },
      () => {
        if (this.state.peopleName.length === 0) {
          this.props.form.setFieldsValue({ pushTarget: "" });
        }
      },
    );
  };

  cancel = () => {
    this.setState(
      {
        people: [],
        peopleName: [],
      },
      () => {
        this.props.handleCancel();
      },
    );
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { modelVisible } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
      },
    };
    return (
      <div className={styles.root}>
        {
          modelVisible ? 
            <TargetSelectModal
              select={this.state.people}
              isMutiple={true}
              selectdesc={this.state.peopleName}
              visible
              closeModal={this.onCancel}
              confirm={this.getPeople}
            />
          : null
        }
        <Modal
          title="人工推送"
          visible={this.props.visible}
          onOk={this.handleSubmit}
          onCancel={this.cancel}
          destroyOnClose
          maskClosable={false}
        >
          <div className={styles.modal}>
            <Form onSubmit={this.handleSubmit}>
              <Form.Item label="场景名称" {...formItemLayout}>
                {getFieldDecorator("templateName", {
                  rules: [{ required: true, message: "请输入场景名称" }],
                })(
                  <Input style={{ width: 358 }} placeholder="请输入场景名称" />,
                )}
              </Form.Item>
              <Form.Item label="场景概述" {...formItemLayout}>
                {getFieldDecorator("templateDescription", {
                  rules: [{ required: true, message: "请输入场景概述" }],
                })(
                  <TextArea
                    style={{ width: 358, height: 120 }}
                    placeholder="请输入场景概述"
                  />,
                )}
              </Form.Item>
              <Form.Item label="推送渠道" {...formItemLayout}>
                {getFieldDecorator("pushChannel", {
                  rules: [{ required: true, message: "请选择推送渠道" }],
                })(
                  <Select style={{ width: 358 }} placeholder="请选择推送渠道">
                    {this.props.channelList.map(item => (
                      <Option
                        value={item.pushChannelId}
                        key={item.pushChannelId}
                      >
                        {item.description}
                      </Option>
                    ))}
                  </Select>,
                )}
              </Form.Item>

              <Form.Item label="推送目标" {...formItemLayout}>
                {getFieldDecorator("pushTarget", {
                  rules: [{ required: true, message: "请选择推送目标" }],
                })(
                  <div
                    className={
                      this.state.borderVisible
                        ? styles.address1
                        : styles.address
                    }
                    onClick={this.setVisible}
                  >
                    {this.state.peopleName.length <= 0 ? (
                      <span
                        style={{
                          color: "rgba(0,0,0,0.25)",
                          height: 32,
                          marginTop: -5,
                          marginLeft: 12,
                        }}
                      >
                        请选择推送目标
                      </span>
                    ) : (
                      this.state.peopleName.map((item, index) => (
                        <Tag
                          closable
                          onClose={() => this.onCloseTag(index)}
                          style={{
                            marginBottom: 5,
                            marginTop: 5,
                            marginLeft: 5,
                            zIndex: 500,
                          }}
                          key={index}
                        >
                          {item}
                        </Tag>
                      ))
                    )}
                  </div>,
                )}
              </Form.Item>
              <Form.Item label="推送文本" {...formItemLayout}>
                {getFieldDecorator("pushText")(
                  <TextArea
                    style={{ width: 358, height: 120 }}
                    placeholder="请输入推送内容"
                  />,
                )}
              </Form.Item>
              <Form.Item label="推送图片" {...formItemLayout}>
                {getFieldDecorator("upload", {
                  valuePropName: "fileList",
                  getValueFromEvent: this.normFile,
                })(
                  <Upload
                    name="file"
                    // action="/msg/simple/pictureToUrl"
                    action="mgt/pictureToUrl"
                    listType="picture"
                    onChange={this.setUrl}
                    accept="image/*"
                    beforeUpload={file => {
                      if (file.type.substring(0, 5) !== "image") {
                        message.error("仅支持上传图片");
                        return false;
                      }
                      if (file.size > 5242880) {
                        message.error("请选择小于5MB的图片");
                        return false;
                      }
                      return true;
                    }}
                  >
                    <Button icon="plus">本地上传</Button>
                    <span
                      style={{
                        fontSize: 12,
                        color: "rgba(0,0,0,0.25)",
                        marginLeft: 8,
                      }}
                    >
                      图片大小应小于5MB
                    </span>
                  </Upload>,
                )}
              </Form.Item>
            </Form>
          </div>
        </Modal>
      </div>
    );
  }
}

export default PushModal;
